package com.zjw.algorithm.utils;

public class ThreadPool {
    private final int size;
    private final Worker[] pools;
    private int pHead;
    private int pTail;
    public ThreadPool(int size) {
        this.size = size;
        this.pTail = size - 1;
        pools = new Worker[size];
        for (int i = 0; i < size; i++) {
            pools[i] = new Worker(i, this);
        }
    }
    public void execute(Runnable task) {
        synchronized (pools) {
            if (pHead == pTail) {
                //max,reject
                return;
            }
            Worker worker = pools[pHead];
            pHead = (pHead + 1) % size;
            worker.start(task);
        }
    }
    private void recycle(Worker worker) {
        synchronized (pools) {
            pTail = (pTail + 1) % size;
            pools[pTail] = worker;
        }
    }
    private static class Worker {
        ThreadPool owner;
        int id;
        public Worker(int id, ThreadPool owner) {
            this.owner = owner;
            this.id = id;
        }
        void start(Runnable r) {
            new Thread(() -> {
                r.run();
                recycle();
            }, "ThreadPool-Work-" + id).start();
        }
        void recycle() {
            owner.recycle(this);
        }
    }
}
